// pages/examine_task_item_page.dart
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sjx/repository/sjx_api.dart';

import '../examine_task_model.dart';
import 'examine_task_cell.dart';

class ExamineTaskItemPage extends StatefulWidget {
  final ExamineTaskType type;
  final String taskNo;
  final VoidCallback onReload;

  const ExamineTaskItemPage({
    Key? key,
    required this.type,
    required this.taskNo,
    required this.onReload,
  }) : super(key: key);

  @override
  _ExamineTaskItemPageState createState() => _ExamineTaskItemPageState();
}

class _ExamineTaskItemPageState extends State<ExamineTaskItemPage> {
  final RefreshController _refreshController = RefreshController();
  final List<ExamineTaskModel> _contentList = [];
  int _pageNum = 1;
  final int _pageSize = 50;
  bool _createTimeASC = true;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadData(showLoading: true);
  }

  Future<void> _loadData({bool showLoading = false}) async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
    });

    if (showLoading) {
      // 显示加载对话框
    }

    try {
      final response = await SJXApi.instance().taskPublishOrder(widget.taskNo, _pageNum, _getStatusStr(widget.type));

      if (_pageNum == 1) {
        _contentList.clear();
      }

      final List<dynamic> dataList = response['taskOrderSumitInfoDtos'] ?? [];
      final List<ExamineTaskModel> newItems = dataList
          .map((item) => ExamineTaskModel.fromJson(item))
          .toList();

      _contentList.addAll(newItems);

      // 更新标题计数
      // 这里可以通过回调更新主页面标题

      setState(() {});

      if (newItems.length < _pageSize) {
        _refreshController.loadNoData();
      } else {
        _refreshController.loadComplete();
      }

    } catch (e) {
      print('加载数据失败: $e');
      _refreshController.loadFailed();
    } finally {
      setState(() {
        _isLoading = false;
      });
      _refreshController.refreshCompleted();
    }
  }

  void _onRefresh() {
    _pageNum = 1;
    _loadData();
    widget.onReload();
  }

  void _onLoadMore() {
    _pageNum++;
    _loadData();
  }

  void _actionSort(bool desc) {
    setState(() {
      _createTimeASC = !desc;
    });
    _onRefresh();
  }

  String _getStatusStr(ExamineTaskType type) {
    return type.displayName;
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: true,
      enablePullUp: true,
      onRefresh: _onRefresh,
      onLoading: _onLoadMore,
      child: _contentList.isEmpty
          ? _buildEmptyView()
          : ListView.builder(
        itemCount: _contentList.length,
        itemBuilder: (context, index) {
          return ExamineTaskCell(
            model: _contentList[index],
            type: widget.type,
            onReload: _onRefresh,
          );
        },
      ),
    );
  }

  Widget _buildEmptyView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.inbox_outlined,
            size: 80,
            color: Colors.grey[300],
          ),
          const SizedBox(height: 16),
          const Text(
            '暂无用户提交',
            style: TextStyle(
              color: Colors.grey,
              fontSize: 16,
            ),
          ),
        ],
      ),
    );
  }
}